/**
 *
 */
package com.ybkj.daijia.api.member.v1;

import com.ybkj.daijia.serverUtils.HttpClientUtil;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.member.ErrorConstant;
import com.ybkj.daijia.api.member.SecurityUtils;
import com.ybkj.daijia.api.member.transport.ResultTransport;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.mc.PassengerAccount;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberPaymentsRecordService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.RateService;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author bo
 *
 */
@Controller("memberProcessController")
@RequestMapping(value = "member/api/rest/v1")
public class ProcessController {

    private static final Logger logger = LoggerFactory.getLogger(ProcessController.class);

    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberAccountService memberAccountService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private MemberPaymentsRecordService memberPaymentsRecordService;
    @Autowired
    private RateService rateService;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;


    /**
     * 主公司电话
     * @param appKey
     * @param token token令牌
     * @param timestamp 时间戳
     * @return
     */
    @RequestMapping(value = "mainPhone", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport mainPhone(String appKey, String token, String timestamp) {

        logger.debug("appKey:{},token:{},timestamp:{}", appKey, token, timestamp);

        if (SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Company mianCompany = companyService.getMain();

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(mianCompany.getTelephone());

            return instance;

        } catch (Exception e) {
            logger.error("api v1 mainPhone error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 分享内容
     */
    @RequestMapping("shareContent")
    public @ResponseBody
    ResultTransport shareContent(String appKey, String token, String timestamp) {

        logger.debug("appKey:{},token:{},timestamp:{}", appKey, token, timestamp);

        if (SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Setting setting = settingUtils.get();

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(setting.getShareContent());

            return instance;

        } catch (Exception e) {
            logger.error("api v1 shareContent error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 加盟内容
     */
    @RequestMapping("businessContent")
    public @ResponseBody
    ResultTransport businessContent(String appKey, String token, String timestamp) {

        logger.debug("appKey:{},token:{},timestamp:{}", appKey, token, timestamp);

        if (SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Setting setting = settingUtils.get();

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(setting.getBusinessContent());

            return instance;

        } catch (Exception e) {
            logger.error("api v1 businessContent error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }


    /**
     * 获取司机地理信息
     * @param id
     * @return
     */
    @RequestMapping(value = "getDriverPlace", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport getDriverPlace(Long driverId, String appKey, String token, String timestamp) {

        logger.debug("recv driverId:{},appKey:{},token:{},timestamp:{}", driverId, appKey, token,
            timestamp);

        if (null == driverId || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverId));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Driver driver = driverService.findOne(driverId);

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS_ERROR);
            }

            Map<String, Object> map = new LinkedHashMap<String, Object>();
            map.put("longitude", driver.getLongitude());
            map.put("latitude", driver.getLatitude());
            try {
                map.put("place", HttpClientUtil
                    .getPlaceByLngAndLat(driver.getLongitude(), driver.getLatitude()));
            } catch (Exception e) {
                logger.error(e.getMessage());
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(map);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 member getDriverPlace error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }
    }

    /**
     * 获取司机
     * @param id
     * @return
     */
    @RequestMapping(value = "getDriver", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport getDriver(Long driverId, String appKey, String token, String timestamp) {

        logger.debug("recv driverId:{},appKey:{},token:{},timestamp:{}", driverId, appKey, token,
            timestamp);

        if (null == driverId || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverId));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Driver driver = driverService.findOne(driverId);

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS_ERROR);
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(driver);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 member getDriver error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }
    }

    /**
     * 获取用户充值记录
     * @param phone 手机号
     * @param appKey
     * @param token token令牌
     * @param timestamp 时间戳
     * @return
     */
    @RequestMapping(value = "rechargeRecord", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport rechargeRecord(String phone, Integer page, Integer limit, String appKey,
        String token, String timestamp) {

        logger.debug("recv phone:{},page:{},limit:{},appKey:{},token:{},timestamp:{}", phone, page,
            limit, appKey, token, timestamp);

        if (StringUtils.isBlank(phone) || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(phone);
        params.add(String.valueOf(page));
        params.add(String.valueOf(limit));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Passenger passenger = memberService.findOnePassengerByPhone(phone);

        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS_ERROR);
        }

        try {

            Page<PassengerAccount> records = null;
            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                records = memberPaymentsRecordService
                    .queryByPassenger(passenger.getId(), "Positive", null, null, page, limit);
            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                records = memberPaymentsRecordService
                    .queryByEnterprise(passenger.getEnterprise_id(), "Positive", null, null, page,
                        limit);
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(records);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 member rechargeRecord error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 获取用户消费记录
     * @param phone 手机号
     * @param appKey
     * @param token token令牌
     * @param timestamp 时间戳
     * @return
     */
    @RequestMapping(value = "consumedRecord", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport consumedRecord(String phone, Integer page, Integer limit, String appKey,
        String token, String timestamp) {

        logger.debug("recv phone:{},page:{},limit:{},appKey:{},token:{},timestamp:{}", phone, page,
            limit, appKey, token, timestamp);

        if (StringUtils.isBlank(phone) || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(phone);
        params.add(String.valueOf(page));
        params.add(String.valueOf(limit));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Passenger passenger = memberService.findOnePassengerByPhone(phone);

        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS_ERROR);
        }

        try {

            Page<PassengerAccount> records = null;
            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                records = memberPaymentsRecordService
                    .queryByPassenger(passenger.getId(), "Negative", null, null, page, limit);
            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                records = memberPaymentsRecordService
                    .queryByEnterprise(passenger.getEnterprise_id(), "Negative", null, null, page,
                        limit);
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(records);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 member consumedRecord error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }


}
